package com.tianbo.elfii.client.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.tianbo.elfii.client.common.ElfiiCommonUtil.FeedBackType;

public class IPSetDialog extends JPanel implements DocumentListener, FocusListener{

	public boolean isLan = true;
	
//	public WlanAP connectingAP;
	
	public JButton confirmBtn;
	public JButton cancelBtn;
	
    BufferedImage bgImg = null;
	
    public JLabel titleLabel = null;
    
    public JTextField staticIpFields[][];
    
    public int focusFieldIndex = 0;
    
    public boolean isUseStaticIP = false;
    public JCheckBox ipStatCheckBox;
    public ImageIcon useStaticIpImg = null;
    public ImageIcon notUseStaticIpImg = null;
    
    public String titleStr = "SSID";
    public String ipStatStr = "使用静态IP";
    
    public int titlePosX = 130;
    
    public Font titleStrFont;
    
    public ElfiiCommonKeyboard keyboard = null;
    
    public boolean isIpIllegal = false;
    public boolean isNetmaskIllegal = false;
    
	public IPSetDialog(){
		titleStr = "以太网静态IP设置";
		isUseStaticIP = !ElfiiCommonConfigUtil.isLanAutoIP;
		titleStrFont = new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,24);
	}
	
	public IPSetDialog(WlanAP connectingAP){
		isLan = false;
//		this.connectingAP = connectingAP;
		titleStr = "Wi-Fi静态IP设置";
		
		isUseStaticIP = !ElfiiCommonConfigUtil.isWlanAutoIP;
		titleStrFont = new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,24);
	}
	
	public void init(){
		this.setLayout(null);
		initImg();
		initBtn();
		initCheckBox();
		initInputField();

	}

	public void initImg(){
        File f;
        try {
            f=new File("resource-common/images/config/wlan/ss_dialog.png");
            bgImg=ImageIO.read(f);
            
            f=new File("resource-common/images/config/ss_07.png");
            useStaticIpImg = new ImageIcon(ImageIO.read(f));
            
            f=new File("resource-common/images/config/ss_06.png");
            notUseStaticIpImg = new ImageIcon(ImageIO.read(f));
            
        } catch(Exception e) {System.out.print(e);}
	}
	
	public void initBtn(){
		confirmBtn = new JButton();
		cancelBtn = new JButton();
		
		confirmBtn.setIcon(new ImageIcon("resource-common/images/login/sssss06.png"));
		cancelBtn.setIcon(new ImageIcon("resource-common/images/login/sssss07.png"));
		
		cancelBtn.setContentAreaFilled(false);
		cancelBtn.setBorder(null);
		cancelBtn.setFocusPainted(false);
		
		confirmBtn.setContentAreaFilled(false);
		confirmBtn.setBorder(null);
		confirmBtn.setFocusPainted(false);

		confirmBtn.setBounds(64, 295, 141, 44);
		cancelBtn.setBounds(245, 295, 141, 44);
		
		this.add(confirmBtn);
		this.add(cancelBtn);
	}
	
	public void initInputField(){
		staticIpFields = new JTextField[5][4];
	    
	    for(int i=0;i<5;i++){
	    	for(int j=0;j<4;j++){
	    		staticIpFields[i][j] = new JTextField(3);
				staticIpFields[i][j].setHorizontalAlignment(JTextField.CENTER);
	    	
	    		this.add(staticIpFields[i][j]);
		    
	    		staticIpFields[i][j].setBounds(130+j*50, 95+i*30, 40, 22);
		    
	    		staticIpFields[i][j].setBorder(null);
	    		
	    		staticIpFields[i][j].setName(String.valueOf(i*4+j));
	    		
	    		staticIpFields[i][j].getDocument().addDocumentListener(this);
	    		staticIpFields[i][j].addFocusListener(this);
	    		
	    		if(j<3){
	    			JLabel gapLabel = new JLabel(".");
	    			gapLabel.setOpaque(true);
	    			gapLabel.setBackground(Color.white);
	    			gapLabel.setForeground(Color.black);
	    			gapLabel.setHorizontalAlignment(JLabel.CENTER);
	    			this.add(gapLabel);
	    			gapLabel.setBounds(170+j*50, 95+i*30, 10, 22);
	    		}
	    	}
	    }
	 
		String ipStrs[];
		String netmaskStrs[];
		String routerStrs[];
		String dns1Strs[];
		String dns2Strs[];
	    
		if(isLan){
			ipStrs = ElfiiCommonConfigUtil.lanStaticIP.ip.split("\\.");
			netmaskStrs = ElfiiCommonConfigUtil.lanStaticIP.netmask.split("\\.");
			routerStrs = ElfiiCommonConfigUtil.lanStaticIP.router.split("\\.");
			dns1Strs = ElfiiCommonConfigUtil.lanStaticIP.dns1.split("\\.");
			dns2Strs = ElfiiCommonConfigUtil.lanStaticIP.dns2.split("\\.");
		}
		else{
			ipStrs = ElfiiCommonConfigUtil.wlanStaticIP.ip.split("\\.");
			netmaskStrs = ElfiiCommonConfigUtil.wlanStaticIP.netmask.split("\\.");
			routerStrs = ElfiiCommonConfigUtil.wlanStaticIP.router.split("\\.");
			dns1Strs = ElfiiCommonConfigUtil.wlanStaticIP.dns1.split("\\.");
			System.out.println("dns2 "+ElfiiCommonConfigUtil.wlanStaticIP.dns2);
			dns2Strs = ElfiiCommonConfigUtil.wlanStaticIP.dns2.split("\\.");
		}
		
//		System.out.println(ElfiiCommonConfigUtil.lanStaticIP.ip+" "+ipStrs.length);
		
		for(int t=0;t<4;t++){
			staticIpFields[0][t].setText(ipStrs[t]);
			staticIpFields[1][t].setText(netmaskStrs[t]);
			staticIpFields[2][t].setText(routerStrs[t]);
			staticIpFields[3][t].setText(dns1Strs[t]);
			staticIpFields[4][t].setText(dns2Strs[t]);
		}
		
		focusFieldIndex = 0;
		staticIpFields[focusFieldIndex/4][focusFieldIndex%4].selectAll();
	} 
	
	
	public void initCheckBox(){
		
		ipStatCheckBox = new JCheckBox();
		
		ipStatCheckBox.setContentAreaFilled(false);
		
		this.add(ipStatCheckBox);
		ipStatCheckBox.setBounds(130, 255, 80, 20);
		
		ipStatCheckBox.setRolloverEnabled(false);
		
		
		if(isUseStaticIP){
			ipStatCheckBox.setSelected(true);
			ipStatCheckBox.setIcon(useStaticIpImg);		
		}
		else{
			ipStatCheckBox.setSelected(false);
			ipStatCheckBox.setIcon(notUseStaticIpImg);
		}
		
		ipStatCheckBox.addItemListener(new ItemListener(){

			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub

				ElfiiCommonUtil.playFeedbackAudio(FeedBackType.CLICK);
				if(ipStatCheckBox.isSelected()){
					
					ipStatCheckBox.setIcon(useStaticIpImg);
					isUseStaticIP = true;
				}
				else{
					ipStatCheckBox.setIcon(notUseStaticIpImg);
					isUseStaticIP = false;
					setIllegalFlag(false);
				}
			}
			
		});
	}
	
	public void setIllegalFlag(boolean flag){

		isIpIllegal = flag;
		isNetmaskIllegal = flag;
		
		this.repaint();
	}
	
	public boolean getInputValidity(){
		boolean ret = true;
		
		if(staticIpFields[0][0].getText().equals("0") && staticIpFields[0][1].getText().equals("0") && staticIpFields[0][2].getText().equals("0") && staticIpFields[0][3].getText().equals("0")){
			isIpIllegal = true;
			this.repaint();
			ret = false;
		}
		
		if(staticIpFields[1][0].getText().equals("0")){
			isNetmaskIllegal = true;
			this.repaint();
			ret = false;
		}
		
		if(isIpIllegal){
			staticIpFields[0][0].requestFocus();
		}
		else if(isNetmaskIllegal){
			staticIpFields[1][0].requestFocus();
		}
		
		return ret;
	}
	
	public IPInfo getInputIP(){
		IPInfo retIPInfo = new IPInfo();
		
		retIPInfo.clear();
		
		for(int t=0;t<4;t++){
			retIPInfo.ip += staticIpFields[0][t].getText();
			retIPInfo.netmask += staticIpFields[1][t].getText();
			retIPInfo.router += staticIpFields[2][t].getText();
			retIPInfo.dns1 += staticIpFields[3][t].getText();
			retIPInfo.dns2 +=staticIpFields[4][t].getText();
			
			if(t!=3){
				retIPInfo.ip += ".";
				retIPInfo.netmask += ".";
				retIPInfo.router += ".";
				retIPInfo.dns1 += ".";
				retIPInfo.dns2 += ".";
			}
		}
		
		return retIPInfo;
	}
	
	public void setFieldBackgroundColor(Color color){
	    for(int i=0;i<5;i++){
	    	for(int j=0;j<4;j++){
	    		staticIpFields[i][j].setBackground(color);
	    	}
	    }
	}
	
	public void setRelatedKeyboard(ElfiiCommonKeyboard keyboard){
		this.keyboard = keyboard;
	}
	
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
      
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(bgImg,null,0,0);

        g2.setColor(Color.white);
        
        g2.setFont(titleStrFont);
    
        g2.drawString(titleStr, titlePosX, 55);
        
        g2.setFont(new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,14));
        
        g2.drawString(" IP地址", 60, 110);
        g2.drawString("网络掩码", 60, 140);
        g2.drawString(" 网 关 ", 60, 170);
        g2.drawString(" DNS1 ", 60, 200);
        g2.drawString(" DNS2 ", 60, 230);
        
        g2.setFont(new Font(ElfiiCommonConstant.Font_Name,Font.PLAIN,12));
        g2.drawString(ipStatStr,150,270);
        
        g2.setColor(ElfiiCommonConstant.Elfii_Red);
        
        if(isIpIllegal){
        	g2.drawString("格式错误", 330, 110);
        }
        
        if(isNetmaskIllegal){
        	g2.drawString("格式错误", 330, 140);
        }
    }

	@Override
	public void insertUpdate(DocumentEvent e) {
		// TODO Auto-generated method stub
		
		switch(focusFieldIndex/4){
		case 0:
			isIpIllegal = false;
			this.repaint();
			break;
		case 1:
			isNetmaskIllegal = false;
			this.repaint();
			break;
		default:
			break;
		}
			
		
		if(e.getDocument().getLength()>=3){

			focusFieldIndex++;
			focusFieldIndex%=20;
			staticIpFields[focusFieldIndex/4][focusFieldIndex%4].requestFocus();
			
			
			if(keyboard!=null){
				keyboard.setTextField(staticIpFields[focusFieldIndex/4][focusFieldIndex%4], 3);
			}
			
//			staticIpFields[focusFieldIndex/4][focusFieldIndex%4].selectAll();

		}
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		// TODO Auto-generated method stub
		switch(focusFieldIndex/4){
		case 0:
			isIpIllegal = false;
			break;
		case 1:
			isNetmaskIllegal = false;
			break;
		default:
			break;
		}
	}

	@Override
	public void changedUpdate(DocumentEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void focusGained(FocusEvent e) {
		// TODO Auto-generated method stub
		focusFieldIndex = Integer.parseInt(((JTextField)e.getSource()).getName());
		
		if(keyboard!=null){
			keyboard.setTextField(staticIpFields[focusFieldIndex/4][focusFieldIndex%4], 3);
		}
	}

	@Override
	public void focusLost(FocusEvent e) {
		// TODO Auto-generated method stub
		
	}
    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame w = new JFrame();
		w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		w.setUndecorated(true); //
		w.setSize(450, 350);
//		w.show();
		IPSetDialog dialog = new IPSetDialog(new WlanAP());
		dialog.setBounds(0, 0, 450, 350);
		dialog.init();
		w.setContentPane(dialog);
		w.show();
	}
}
